package com.btg.set.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.btg.set.BtgSetPlugin;
import com.btg.set.util.BtgSetHelper;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/11/28.
 */
public class BtgSetServlet extends ResourceServlet {

    public BtgSetServlet() {
        super("support/http/resources");
    }

    public JSONObject query(JSONObject params) {

        String sql = "select * from btg_set_cfg_module order by state desc";
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        JSONObject reJson = new JSONObject();
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            JSONArray arr = new JSONArray();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                JSONObject json = new JSONObject();
                json.put("key_id", rs.getString("key_id"));
                json.put("set_code", rs.getString("set_code"));
                json.put("set_name", rs.getString("set_name"));
                json.put("set_desc", rs.getString("set_desc"));
                json.put("state", rs.getString("state"));
                arr.add(json);
            }
            reJson.put("data", arr);
            return succ(reJson);
        } catch (Exception e) {
            e.printStackTrace();
            reJson.put("msg", "获取参数配置环境失败!");
            return error(reJson);
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (statement != null)
                    statement.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public JSONObject initEvn(JSONObject params) {
        //构造参数环境
        BtgSetHelper.getInstance().resetDataBaseEnv();
        //写入默认配置
        BtgSetHelper.getInstance().writeDefaultSet();
        //启用默认配置
        BtgSetHelper.getInstance().initValue();
        return succ(new JSONObject());
    }

    /**
     * 复制默认模板
     */
    public JSONObject copyDef(JSONObject params) {
        String setName = params.getString("set_name");
        String setCode = params.getString("set_code");
        String remark = params.getString("remark");

        if (exists(setName, setCode)) {
            JSONObject obj = new JSONObject();
            obj.put("msg", "配置代码或名称已存在！");
            return error(obj);
        }

        String sql = "select * from btg_set_cfg_module where set_code='default'";
        Connection conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
        Statement statement = null;
        PreparedStatement pstms = null;
        ResultSet rs = null;
        JSONObject reJson = new JSONObject();
        try {
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            JSONObject json = new JSONObject();
            while (rs.next()) {
                json.put("key_id", rs.getString("key_id"));
                json.put("set_code", rs.getString("set_code"));
                json.put("set_name", rs.getString("set_name"));
                json.put("set_desc", rs.getString("set_desc"));
                json.put("state", rs.getString("state"));
            }

            String keyId = UUID.randomUUID().toString().replaceAll("-", "");
            sql = "insert into btg_set_cfg_module(key_id,set_code,set_name,set_desc,state)";
            sql += "values(?,?,?,?,0)";
            pstms = conn.prepareStatement(sql);
            pstms.setString(1, keyId);
            pstms.setString(2, setCode);
            pstms.setString(3, setName);
            pstms.setString(4, remark);
            pstms.execute();
            pstms.clearParameters();

            //保存值
            sql = "select * from btg_set_cfg_miv where module_code='default'";
            rs = statement.executeQuery(sql);
            sql = "insert into btg_set_cfg_miv(key_id,module_id,module_code,item_code,item_value,remark,i_time)";
            sql += "values(?,?,?,?,?,?,?)";
            while (rs.next()) {
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String mivId = UUID.randomUUID().toString().replaceAll("-", "");
                pstms = conn.prepareStatement(sql);
                pstms.setString(1, mivId);
                pstms.setString(2, keyId);
                pstms.setString(3, setCode);
                pstms.setString(4, rs.getString("item_code"));
                pstms.setString(5, rs.getString("item_value"));
                pstms.setString(6, rs.getString("remark"));
                pstms.setString(7, sf.format(new java.util.Date()));
                pstms.execute();
                pstms.clearParameters();
            }
            return succ(reJson);
        } catch (SQLException e) {
            e.printStackTrace();
            reJson.put("msg", "复制默认模板失败！");
            return error(reJson);
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (statement != null)
                    statement.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean exists(String setName, String setCode) {
        String sql = "select * from btg_set_cfg_module where set_name=? or set_code=?";
        Connection conn = null;
        PreparedStatement pstms = null;
        ResultSet rs = null;
        boolean con = false;
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            pstms = conn.prepareStatement(sql);
            pstms.setString(1, setName);
            pstms.setString(2, setCode);
            rs = pstms.executeQuery();

            while (rs.next()) {
                con = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (pstms != null)
                    pstms.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }


    public JSONObject sub(JSONObject params) {
        String keyId = params.getString("module");
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            if (keyId == null || "".equals(keyId)) {
                String sql = "select * from btg_set_cfg_module where state=1";
                statement = conn.createStatement();
                rs = statement.executeQuery(sql);
                while (rs.next()) {
                    keyId = rs.getString("key_id");
                }
            }
            String sql = "select t.*,i.item_name,i.item_desc,i.data_type,i.group_name from btg_set_cfg_miv t,btg_set_cfg_item i where t.item_code=i.item_code and  t.module_id='" + keyId + "' order by index_no";
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            List<String> moduleList = new ArrayList<String>();
            JSONArray arr = new JSONArray();
            while (rs.next()) {
                JSONObject json = new JSONObject();
                json.put("key_id", rs.getString("key_id"));
                json.put("module_id", rs.getString("module_id"));
                json.put("module_code", rs.getString("module_code"));
                json.put("item_code", rs.getString("item_code"));
                json.put("item_value", rs.getString("item_value"));
                json.put("remark", rs.getString("remark"));
                json.put("item_name", rs.getString("item_name"));
                json.put("item_desc", rs.getString("item_desc"));
                json.put("data_type", rs.getString("data_type"));
                json.put("group_name", rs.getString("group_name"));
                if (!moduleList.contains(json.getString("group_name"))) {
                    moduleList.add(json.getString("group_name"));
                }
                arr.add(json);
            }

            JSONArray re = new JSONArray();
            for (String s : moduleList) {
                JSONObject json = new JSONObject();
                json.put("group_name", s);
                JSONArray data = new JSONArray();
                for (int i = 0; i < arr.size(); i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    if (obj.getString("group_name").equals(s)) {
                        data.add(obj);
                    }
                }
                json.put("data", data);
                re.add(json);
            }
            JSONObject obj = new JSONObject();
            obj.put("key_id", keyId);
            obj.put("re", re);
            return succ(obj);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put("msg", "获取配置信息失败！");
            return error(obj);
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (statement != null)
                    statement.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public JSONObject save(JSONObject params) {
        String data = params.getString("data");
        JSONArray arr = JSONArray.parseArray(data);
        String keyId = params.getString("key_id");
        Connection conn = null;
        PreparedStatement pstate = null;
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String sql = "update btg_set_cfg_miv set item_value=?,u_time=? where module_id=? and item_code=?";
            for (int i = 0; i < arr.size(); i++) {
                pstate = conn.prepareCall(sql);
                JSONObject tmp = arr.getJSONObject(i);
                pstate.setString(1, tmp.getString("item_value"));
                pstate.setString(2, sf.format(new java.util.Date()));
                pstate.setString(3, keyId);
                pstate.setString(4, tmp.getString("item_code"));
                pstate.execute();
                pstate.clearParameters();
            }
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put("msg", "保存配置信息失败！");
            return error(obj);
        } finally {
            try {
                if (pstate != null)
                    pstate.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public JSONObject apply(JSONObject params) {
        String keyId = params.getString("key_id");
        Connection conn = null;
        Statement stat = null;
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            String sql = "update btg_set_cfg_module set state=0";
            stat = conn.createStatement();
            stat.execute(sql);
            sql = "update btg_set_cfg_module set state=1 where key_id='" + keyId + "'";
            stat.execute(sql);
            BtgSetHelper.getInstance().initValue(keyId);
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put("msg", "保存配置信息失败！");
            return error(obj);
        } finally {
            try {
                if (stat != null)
                    stat.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public JSONObject del(JSONObject params) {
        String keyId = params.getString("key_id");
        Connection conn = null;
        Statement stat = null;
        try {
            conn = BtgSetPlugin.getBtgSetPlugin().getConnection();
            String sql = "delete from  btg_set_cfg_module   where key_id='" + keyId + "'";
            stat = conn.createStatement();
            stat.execute(sql);
            sql = "delete from btg_set_cfg_miv where module_id='" + keyId + "'";
            stat.execute(sql);
            return succ(new JSONObject());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject obj = new JSONObject();
            obj.put("msg", "删除配置信息失败！");
            return error(obj);
        } finally {
            try {
                if (stat != null)
                    stat.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private JSONObject succ(JSONObject reJeson) {
        reJeson.put("code", "0000");
        if (!reJeson.containsKey("msg"))
            reJeson.put("msg", "请求成功！");
        return reJeson;
    }

    private JSONObject error(JSONObject reJeson) {
        reJeson.put("code", "9999");
        if (!reJeson.containsKey("msg"))
            reJeson.put("msg", "请求失败！");
        return reJeson;
    }
}
